<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>批改试卷 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题   这是老师批改学生考试的页面 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
            'status-pending': '#FFB800',
            'status-active': '#36D399',
            'status-expired': '#94A3B8'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-exam {
        @apply bg-secondary text-white px-3 py-1.5 rounded-lg transition-all duration-300 hover:bg-secondary/90 active:bg-secondary/80;
      }
      .status-badge {
        @apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium;
      }
      .status-pending {
        @apply bg-yellow-100 text-yellow-800;
      }
      .status-graded {
        @apply bg-green-100 text-green-800;
      }
      .question-card {
        @apply border border-gray-200 rounded-lg p-4 mb-4;
      }
      .answer-correct {
        @apply bg-green-50 border-green-200 text-green-800;
      }
      .answer-incorrect {
        @apply bg-red-50 border-red-200 text-red-800;
      }
      .answer-partial {
        @apply bg-yellow-50 border-yellow-200 text-yellow-800;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors relative">
            <i class="fa fa-bell-o"></i>
            <span class="absolute -top-1 -right-1 w-4 h-4 bg-accent text-white text-xs rounded-full flex items-center justify-center">3</span>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">{{ teacher.name if teacher else '教师' }}</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 container mx-auto px-4 py-6">
    <!-- 页面标题 -->
    <div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
      <div>
        <h2 class="text-2xl font-bold text-neutral-dark mb-2">批改试卷</h2>
        <div class="flex flex-wrap items-center gap-3 text-sm text-gray-500">
          <span><i class="fa fa-user mr-1"></i>{{ student.name }}</span>
          <span><i class="fa fa-book mr-1"></i>{{ exam.subject }}</span>
        </div>
      </div>

      <div class="flex items-center gap-3">
        <div class="text-sm">
          <span class="text-gray-500">当前得分：</span>
          <span class="font-semibold text-primary">{{ "%.1f"|format(total_score) if total_score is not none else '未评分' }}</span>
        </div>
        <div class="text-sm">
          <span class="text-gray-500">总分：</span>
          <span class="font-semibold text-secondary">{{ "%.1f"|format(max_score) }}</span>
        </div>
      </div>
    </div>

    <!-- 自动批改按钮 -->
    <div class="mb-4 flex justify-end">
      <button id="auto-grade-btn" class="btn-secondary mr-3">
        <i class="fa fa-magic mr-2"></i>自动批改选择题
      </button>
      <button id="auto-text-grade-btn" class="btn-secondary mr-3">
        <i class="fa fa-magic mr-2"></i>自动批改填空题和简答题
      </button>
    </div>

    <!-- 试卷内容 -->
    <div class="bg-white rounded-xl card-shadow p-6 mb-6">
      <div class="space-y-6">
        {% for question in questions %}
        <div class="question-card {{ 'answer-correct' if question.is_correct == True else ('answer-incorrect' if question.is_correct == False else '') }}" data-question-id="{{ question.question_id }}">
          <div class="flex items-start gap-4 mb-3">
            <div class="w-8 h-8 rounded-full bg-primary/10 text-primary flex items-center justify-center font-semibold text-sm">{{ loop.index }}</div>
            <div class="flex-1">
              <div class="flex flex-wrap items-center gap-2 mb-2">
                <span class="inline-flex items-center px-2 py-0.5 text-xs bg-primary/10 text-primary rounded-full">{{ question.type }}</span>
                <span class="inline-flex items-center px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded-full">分值：{{ question.score }}</span>
                {% if question.is_correct == True %}
                  <span class="inline-flex items-center px-2 py-0.5 text-xs bg-green-100 text-green-800 rounded-full">
                    <i class="fa fa-check mr-1"></i>正确
                  </span>
                {% elif question.is_correct == False %}
                  <span class="inline-flex items-center px-2 py-0.5 text-xs bg-red-100 text-red-800 rounded-full">
                    <i class="fa fa-times mr-1"></i>错误
                  </span>
                {% endif %}
              </div>
              <p class="text-base leading-relaxed">{{ question.question }}</p>
            </div>
          </div>

          <!-- 题目选项 -->
          {% if question.options %}
          <div class="mb-3 ml-12 space-y-2">
            {% for option in question.options %}
            <div class="flex items-start gap-2">
              <span class="font-medium">{{ option.label }}.</span>
              <span>{{ option.content }}</span>
            </div>
            {% endfor %}
          </div>
          {% endif %}

          <!-- 正确答案 -->
          <div class="mb-3 ml-12">
            <span class="text-sm text-gray-500">正确答案：</span>
            <span class="font-medium">{{ question.correct_answer }}</span>
          </div>

          <!-- 学生答案 -->
          <div class="mb-3 ml-12">
            <span class="text-sm text-gray-500">学生答案：</span>
            {% if question.student_answer %}
              <span class="font-medium">{{ question.student_answer }}</span>
            {% else %}
              <span class="text-gray-400">未作答</span>
            {% endif %}
          </div>

          <!-- 批改输入 -->
          <div class="ml-12">
            <div class="flex items-center gap-3">
              <span class="text-sm text-gray-500">本题得分：</span>
              <input type="number"
                name="question-{{ question.question_id }}-score"
                class="w-20 px-2 py-1 border border-gray-200 rounded focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary text-sm"
                min="0"
                max="{{ question.score }}"
                step="0.5"
                value="{{ question.current_score if question.current_score is not none else 0 }}">
              <span class="text-sm text-gray-500">/ {{ question.score }}</span>
            </div>
          </div>
        </div>
        {% endfor %}
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="flex justify-end gap-3">
      <a href="{{ url_for('Correction.correction_page', exam_id=exam.id) }}" class="btn-secondary">
        <i class="fa fa-arrow-left mr-2"></i>返回列表
      </a>
      <button id="save-grade-btn" class="btn-primary">
        <i class="fa fa-save mr-2"></i>保存批改
      </button>
    </div>
  </main>

  <script>
    // 计算总分
    function calculateTotalScore() {
      const scoreInputs = document.querySelectorAll('input[name^="question-"][name$="-score"]');
      let total = 0;

      scoreInputs.forEach(input => {
        const value = parseFloat(input.value) || 0;
        total += value;
      });

      // 更新显示的总分
      const totalScoreElement = document.querySelector('.font-semibold.text-primary');
      if (totalScoreElement) {
        totalScoreElement.textContent = total.toFixed(1);
      }

      return total;
    }

    // 初始化时计算总分
    calculateTotalScore();

    // 监听所有得分输入的变化
    document.querySelectorAll('input[name^="question-"][name$="-score"]').forEach(input => {
      input.addEventListener('input', calculateTotalScore);
    });

    // 自动批改选择题
    document.getElementById('auto-grade-btn').addEventListener('click', async function() {
      try {
        const response = await fetch('{{ url_for("Correction.auto_grade", exam_id=exam.id, student_id=student.id) }}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const result = await response.json();

        if (result.success) {
          alert('自动批改完成！选择题和多选题已自动评分。');
          // 刷新页面以显示更新后的分数
          window.location.reload();
        } else {
          alert('自动批改失败：' + result.message);
        }
      } catch (error) {
        console.error('自动批改时出错:', error);
        alert('自动批改失败，请重试');
      }
    });

    // 保存批改
    document.getElementById('save-grade-btn').addEventListener('click', async function() {
      const scoreInputs = document.querySelectorAll('input[name^="question-"][name$="-score"]');
      const questionScores = {};

      scoreInputs.forEach(input => {
        const questionId = input.name.replace('question-', '').replace('-score', '');
        questionScores[questionId] = parseFloat(input.value) || 0;
      });

      const totalScore = calculateTotalScore();

      try {
        const response = await fetch('{{ url_for("Correction.submit_grade", exam_id=exam.id, student_id=student.id) }}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            question_scores: questionScores
          })
        });

        const result = await response.json();

        if (result.success) {
          alert('批改结果已保存！');
          // 可选：重定向回列表页面
          window.location.href = '{{ url_for("Correction.correction_page", exam_id=exam.id) }}';
        } else {
          alert('保存失败：' + result.message);
        }
      } catch (error) {
        console.error('保存批改结果时出错:', error);
        alert('保存失败，请重试');
      }
    });
    //自动批改填空题和简答题
    document.getElementById('auto-text-grade-btn').addEventListener('click', async function() {
      try {
        const response = await fetch('{{ url_for("Correction.auto_text_grade", exam_id=exam.id, student_id=student.id) }}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const result = await response.json();

        if (result.success) {
          alert(result.message);
          
          // 如果返回了问题数据，更新页面而不刷新
          if (result.questions && result.questions.length > 0) {
            // 更新总分
            const totalScoreElement = document.querySelector('.font-semibold.text-primary');
            if (totalScoreElement) {
              totalScoreElement.textContent = result.total_score.toFixed(1);
            }
            
            // 更新每个问题的分数
            result.questions.forEach(question => {
              const scoreInput = document.querySelector(`input[name="question-${question.question_id}-score"]`);
              if (scoreInput) {
                scoreInput.value = question.current_score;
                
                // 触发input事件以更新总分
                const event = new Event('input', { bubbles: true });
                scoreInput.dispatchEvent(event);
              }
            });
          } else {
            // 如果没有返回问题数据，刷新页面
            window.location.reload();
          }
        } else {
          alert('自动批改失败：' + result.message);
        }
      } catch (error) {
        console.error('自动批改时出错:', error);
        alert('自动批改失败，请重试');
      }
    });

  </script>
</body>
</html>